<?php

namespace App\Classes\Injection;

use App\Models\Entity\Assets\Assets;
use App\Models\Injection\InjectAssetiHistory;
use App\Models\Common\CatData\Video\Vcat;
use App\Models\Common\EntityData\Channel\Sp;
use App\Models\Common\EntityData\Video\Actor;
use App\Models\Common\EntityData\Video\Director;
use App\Models\Common\Enumdata\Enumop\Video\Varea;
use App\Models\Common\Enumdata\Enumop\Video\Vlang;
use App\Models\Common\Enumdata\Enumop\Video\Vyear;
use App\Models\Common\Enumdata\File\Video\Vfileext;
use App\Models\Common\Enumdata\Video\Resolution;
use App\Models\Common\TagData\Video\Vcattag;
use App\Models\Entity\Asset\Video\Media\Vifile;
use App\Models\Entity\Asset\Video\Media\Vposteri;
use App\Models\Entity\Asset\Video\Vasseti;
use App\Models\Entity\Asset\Video\Vseriali;
use App\Models\Entity\Asset\Iaasset;
use App\Models\Entity\Asset\Iaseriali;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\Log;
use DB;
use Storage;
use FTP;

/**
 * 媒资注入自定义类
 */
class importCms
{

    /**
     * [$inportCmsWhere 导入的条件]
     * @var array
     */
    protected $importCmsWhere = ['online_status' => 1];

    /**
     * [$ids description]
     * @var [type]
     */
    protected $ids;

    /**
     * { 判断是单个剧集还是多个剧集 }
     *
     * @var        boolean
     */
    public $flag = false;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct( $ids = null)
    {
        $this->ids                  = $ids;
        if (!is_null($ids)) {
            if (is_array($ids)) {
                $this->flag           = true;
            }
        }
    }

    /**
     * 发起媒资导入CMS
     *
     * @return contnet
     */
    public function handle()
    {

        $assetis = Assets::whereIn('id', $this->ids)->get();

        // 注入媒资总数
        $importCmsVasseticount = count($assetis);
        // 错误的行数
        $errorRow = [];

        $success_count = 0;

        foreach ($assetis as $asseti) {

            if($asseti->inject_datetime == 0){
                $errorRow[] ="媒资ID: ". $asseti->id ." 错误信息: 还未完成注入,不用倒入CMS<br>";
                continue;
            }
            switch ($asseti->asset_type){
                   //视频导入
                   case 'asset':
                       if($asseti->pid == '0'){
                           //导入总集
                           $rs = self::importVideoVasseti($asseti);
                       }else{
                           //导入分集
                           $rs = self::importVideoVseriali($asseti);
                       }
                       break;
                   //音频导入
                   case 'aasset':
                       if($asseti->pid == '0'){
                           //导入总集
                           $rs = self::importVideoIaasset($asseti);
                       }else{
                           //导入分集
                           $rs = self::importVideoIaseriali($asseti);
                       }
                       break;
                   case 'lvasset':
                       break;
                   case 'laasset':
                       break;
            }

            if($rs === true){
                $success_count++;
            }else{
                $errorRow[] ="媒资ID: ". $asseti->id ." 错误信息: ". $rs;
            }

        }

        $flag       = true;
        $errorCount = count($errorRow);
        $message    = '<div style="word-wrap: break-word;">';
        $message .= '导入总数:';
        $message .= $importCmsVasseticount. '<br />';
        $message .= '导入成功数:';
        $message .= $success_count . '<br />';
        $message .= '导入失败数:';
        $message .= $errorCount . '<br />';
        if ($errorCount > 0) {
            $message .= '导入失败数据:<br>';
            $flag = false;
            foreach ($errorRow as $error){
                $message .= $error.'<br>';
            }
        }
        $message .= '</div>';
        //通过标志位判断前端返回时成功还是失败
        if ($flag) {
            $message = '<div class="alert alert-success">' . $message . '</div>';
        } else {
            $message = '<div class="alert alert-error">' . $message . '</div>';
        }

        return $message;
    }

    //视频总集导入CMS
    public static function importVideoVasseti($data){
        // 检查必须字段数据
        if(empty($data->spid)){
            return '缺少SP编号信息';
        }

        if(empty($data->spasset_id)){
            return '缺少SP媒资ID数据';
        }

        if(empty($data->vcat_id)){
            return '缺少媒资vcat_id数据';
        }

        if(empty($data->title)){
            return '缺少媒资 title 数据';
        }

        // 每次插入开启事务
        DB::beginTransaction();
        try {

            $flag = true;

            // 需要将归类转成id
            if ($vcat1 = Vcat::where('name', $data->vcat_id)->first()) {
                $class = $vcat1->id;
            } else {
                $vcat             = new Vcat;
                $vcat->name       = $data->vcat_id;
                $vcat->short_desc = $data->vcat_id;
                $vcat->save();
                $class = $vcat->id;
            }


            $asset = Vasseti::where('vasseti_no', $data->spasset_id)->first();
            if(empty($asset)){
                $asset = new Vasseti;
            }
            // 编号
            $asset->vasseti_no = $data->spasset_id;
            // 剧集名称
            $asset->name = $data->title;
            $asset->title = $data->title;
            $asset->subtitle = $data->subtitle;
            // 评分
            $asset->score = $data->score;
            // 集数
            $asset->episode = $data->episode;
            // 季
            $asset->season = $data->season;
            // 归类
            $asset->vcat_id = $class;
            // 简介
            $asset->short_desc = $data->short_desc;
            // 详情
            $asset->long_desc = $data->desc;
            // // 上映时间
            // $asset->firstdate = $release_time;
            $asset->online_status = 0;
            $asset->moderate_status = 0;
            $asset->publish_status = 0;
            $asset->publish_down_status = 0;
            $asset->user_id = Admin::user()->id;

            // 收费类型
            $asset->charge_type = 0;

            //是否有剧集 电视剧总集或者单集电影
            if(empty($data->pid) && empty($data->file_url)){
                $asset->vasseti_type = 1;
            }else{
                $asset->vasseti_type = 0;
            }

            $asset->serials = $data->serials;
            $asset->upto = $data->upto;
            if ($asset->save()) {
                if (!empty($data->spid)) {
                    $rs = self::importSp($data->spid);
                    if($rs === false){
                        $flag = false;
                        throw exception("导入SP数据失败");
                    }else{
                        $asset->sps()->sync($rs);
                    }
                }
                //导入演员信息
                if (!empty($data->actors)) {
                    $rs = self::importActors($data->actors);
                    if($rs === false){
                        $flag = false;
                        throw exception("导入演员数据失败");
                    }else{
                        $asset->actors()->sync($rs);
                    }
                }
                //导入导演信息
                if (!empty($data->directors)) {
                    $rs = self::importDirector($data->directors);
                    if($rs === false){
                        $flag = false;
                        throw exception("导入导演数据失败");
                    }else{
                        $asset->directors()->sync($rs);
                    }
                }
                //导入地区信息
                if (!empty($data->varea)) {
                    $rs = self::importVarea($data->varea);
                    if($rs === false){
                        $flag = false;
                        throw exception("导入地区数据失败");
                    }else{
                        $asset->vareas()->sync($rs);
                    }
                }
                //导入语言信息
                if (!empty($data->vlangs)) {
                    $rs = self::importVlangs($data->vlangs);
                    if($rs === false){
                        $flag = false;
                        throw exception("导入语言数据失败");
                    }else{
                        $asset->vlangs()->sync($rs);
                    }

                }
                //导入年代信息
                if (!empty($data->vyears)) {
                    $rs = self::importVyears($data->vyears);
                    if($rs === false){
                        $flag = false;
                        throw exception("导入年代数据失败");
                    }else{
                        $asset->vyears()->sync($rs);
                    }
                }
                //导入海报信息
                $vposteris = [
                    '1'=>$data->pic0,
                    '2'=>$data->pic1,
                    '3'=>$data->pic2,
                    '4'=>$data->pic3,
                    '5'=>$data->pic4,
                    '6'=>$data->pic5,
                ];
                if (!empty($vposteris)) {
                    $rs = self::importVposteris($vposteris);
                    if($rs === false){
                        $flag = false;
                        throw exception("导入海报数据失败");
                    }else{
                        $asset->vposteris()->sync($rs);
                    }
                }
                //导入片源信息
                if (!empty($data->file_url)) {
                    $rs = self::importVfiles($data);
                    if($rs === false){
                        $flag = false;
                        throw exception("导入媒资文件数据失败");
                    }else{
                        $asset->vifiles()->sync($rs);
                    }
                }
            }else{
                $flag = false;
            }


            if ($flag) {
                DB::commit();
            } else {
                DB::rollback();
            }
        }catch (\Exception $e) {
            DB::rollback(); //事务回滚
            return $e->getMessage();
        }

        return $flag;
    }


    //视频分集导入CMS
    public static function importVideoVseriali($data){
        // 检查必须字段数据
        if(empty($data->episode)){
            return '缺少episode信息';
        }

        if(empty($data->spasset_id)){
            return '缺少SP媒资ID数据';
        }

        if(empty($data->title)){
            return '缺少媒资 title 数据';
        }

        // 每次插入开启事务
        DB::beginTransaction();
        try {

            $flag = true;

            $Vasseti = Vasseti::where('vasseti_no', $data->pid)->first();
            if ($Vasseti) {
                $vseriali = Vseriali::where('vseriali_no',$data->spasset_id)
                                     ->where('vasseti_id',$Vasseti->id)
                                     ->first();
                if(empty($vseriali)){
                    $vseriali = new Vseriali;
                }
                // 剧集id
                $vseriali->vasseti_id = $Vasseti->id;
                // 分集编号
                $vseriali->vseriali_no = $data->spasset_id;
                // 分集名称
                $vseriali->name = $data->title;
                // 集数
                $vseriali->episode =$data->episode;
                // 简介
                $vseriali->short_desc = $data->short_desc;
                // 详情
                $vseriali->long_desc = $data->long_desc;
                // 评分
                $vseriali->score = $data->score;
                // 上映时间
                $vseriali->firstdate = $data->vyears ? strtotime($data->vyears) : null;
                // 文件
                if ($vseriali->save()) {
                    // 图片
                    //导入海报信息
                    $vposteris = [
                        '1'=>$data->pic0,
                        '2'=>$data->pic1,
                        '3'=>$data->pic2,
                        '4'=>$data->pic3,
                        '5'=>$data->pic4,
                        '6'=>$data->pic5,
                    ];
                    if (!empty($vposteris)) {
                        $rs = self::importVposteris($vposteris);
                        if($rs === false){
                            $flag = false;
                            throw exception("导入海报数据失败");
                        }
                        if (!empty($rs)) {
                            $vseriali->vposteris()->sync($rs);
                        }
                    }
                    //导入片源信息
                    if (!empty($data->file_url)) {
                        $rs = self::importVfiles($data);
                        if($rs === false){
                            $flag = false;
                            throw exception("导入媒资文件数据失败");
                        }else{
                            $vseriali->vifiles()->sync($rs);
                        }
                    }
                }else{
                    $flag = false;
                }

                if ($flag) {
                    DB::commit();
                } else {
                    DB::rollback();
                }
            }else{
                return '缺少主媒资数据,请先导入主媒资';
            }
        }catch (\Exception $e) {
            DB::rollback(); //事务回滚
            return $e->getMessage();
        }

        return $flag;
    }


    //音频总集导入CMS
    public static function importVideoIaasset($data){
        // 检查必须字段数据
        if(empty($data->spid)){
            return '缺少SP编号信息';
        }

        if(empty($data->spasset_id)){
            return '缺少SP媒资ID数据';
        }

        if(empty($data->vcat_id)){
            return '缺少媒资vcat_id数据';
        }

        if(empty($data->title)){
            return '缺少媒资 title 数据';
        }

        // 每次插入开启事务
        DB::beginTransaction();
        try {

            $flag = true;

            // 需要将归类转成id
            if ($vcat1 = Vcat::where('name', $data->vcat_id)->first()) {
                $class = $vcat1->id;
            } else {
                $vcat             = new Vcat;
                $vcat->name       = $data->vcat_id;
                $vcat->short_desc = $data->vcat_id;
                $vcat->save();
                $class = $vcat->id;
            }


            $asset = Iaasset::where('iaasset_no', $data->spasset_id)->first();
            if(empty($asset)){
                $asset = new Iaasset;
            }
            // 编号
            $asset->iaasset_no = $data->spasset_id;
            // 剧集名称
            $asset->name = $data->title;
            $asset->title = $data->title;
            $asset->subtitle = $data->subtitle;
            // 评分
            $asset->score = $data->score;
            // 集数
            $asset->episode = $data->episode;
            // 季
            $asset->season = $data->season;
            // 归类
            $asset->vcat_id = $class;
            // 简介
            $asset->short_desc = $data->short_desc;
            // 详情
            $asset->long_desc = $data->desc;
            // // 上映时间
            // $asset->firstdate = $release_time;
            $asset->online_status = 0;
            $asset->moderate_status = 0;
            $asset->publish_status = 0;
            $asset->publish_down_status = 0;
            $asset->user_id = Admin::user()->id;

            // 收费类型
            $asset->charge_type = 0;

            //是否有剧集 电视剧总集或者单集电影
            if(empty($data->pid) && empty($data->file_url)){
                $asset->iaasset_type = 1;
            }else{
                $asset->iaasset_type = 0;
            }

            $asset->serials = $data->serials;
            $asset->upto = $data->upto;
            if ($asset->save()) {
                if (!empty($data->spid)) {
                    $rs = self::importSp($data->spid);
                    if($rs === false){
                        $flag = false;
                        throw exception("导入SP数据失败");
                    }else{
                        $asset->sps()->sync($rs);
                    }
                }
                //导入演员信息
                if (!empty($data->actors)) {
                    $rs = self::importActors($data->actors);
                    if($rs === false){
                        $flag = false;
                        throw exception("导入演员数据失败");
                    }else{
                        $asset->actors()->sync($rs);
                    }
                }
                //导入导演信息
                if (!empty($data->directors)) {
                    $rs = self::importDirector($data->directors);
                    if($rs === false){
                        $flag = false;
                        throw exception("导入导演数据失败");
                    }else{
                        $asset->directors()->sync($rs);
                    }
                }
                //导入地区信息
                if (!empty($data->varea)) {
                    $rs = self::importVarea($data->varea);
                    if($rs === false){
                        $flag = false;
                        throw exception("导入地区数据失败");
                    }else{
                        $asset->vareas()->sync($rs);
                    }
                }
                //导入语言信息
                if (!empty($data->vlangs)) {
                    $rs = self::importVlangs($data->vlangs);
                    if($rs === false){
                        $flag = false;
                        throw exception("导入语言数据失败");
                    }else{
                        $asset->vlangs()->sync($rs);
                    }

                }
                //导入年代信息
                if (!empty($data->vyears)) {
                    $rs = self::importVyears($data->vyears);
                    if($rs === false){
                        $flag = false;
                        throw exception("导入年代数据失败");
                    }else{
                        $asset->vyears()->sync($rs);
                    }
                }
                //导入海报信息
                $vposteris = [
                    '1'=>$data->pic0,
                    '2'=>$data->pic1,
                    '3'=>$data->pic2,
                    '4'=>$data->pic3,
                    '5'=>$data->pic4,
                    '6'=>$data->pic5,
                ];
                if (!empty($vposteris)) {
                    $rs = self::importVposteris($vposteris);
                    if($rs === false){
                        $flag = false;
                        throw exception("导入海报数据失败");
                    }else{
                        $asset->vposteris()->sync($rs);
                    }
                }
                //导入片源信息
                if (!empty($data->file_url)) {
                    $rs = self::importVfiles($data);
                    if($rs === false){
                        $flag = false;
                        throw exception("导入媒资文件数据失败");
                    }else{
                        $asset->vifiles()->sync($rs);
                    }
                }
            }else{
                $flag = false;
            }


            if ($flag) {
                DB::commit();
            } else {
                DB::rollback();
            }
        }catch (\Exception $e) {
            DB::rollback(); //事务回滚
            return $e->getMessage();
        }

        return $flag;
    }


    //音频分集导入CMS
    public static function importVideoIaseriali($data){
        // 检查必须字段数据
        if(empty($data->episode)){
            return '缺少episode信息';
        }

        if(empty($data->spasset_id)){
            return '缺少SP媒资ID数据';
        }

        if(empty($data->title)){
            return '缺少媒资 title 数据';
        }

        // 每次插入开启事务
        DB::beginTransaction();
        try {

            $flag = true;

            $Vasseti = Iaasset::where('iaasset_no', $data->pid)->first();
            if ($Vasseti) {
                $vseriali = Iaseriali::where('iaseriali_no',$data->spasset_id)
                    ->where('vasseti_id',$Vasseti->id)
                    ->first();
                if(empty($vseriali)){
                    $vseriali = new Iaseriali;
                }
                // 剧集id
                $vseriali->iaasset_id = $Vasseti->id;
                // 分集编号
                $vseriali->iaseriali_no = $data->spasset_id;
                // 分集名称
                $vseriali->name = $data->title;
                // 集数
                $vseriali->episode =$data->episode;
                // 简介
                $vseriali->short_desc = $data->short_desc;
                // 详情
                $vseriali->long_desc = $data->long_desc;
                // 评分
                $vseriali->score = $data->score;
                // 上映时间
                $vseriali->firstdate = $data->vyears ? strtotime($data->vyears) : null;
                // 文件
                if ($vseriali->save()) {
                    // 图片
                    //导入海报信息
                    $vposteris = [
                        '1'=>$data->pic0,
                        '2'=>$data->pic1,
                        '3'=>$data->pic2,
                        '4'=>$data->pic3,
                        '5'=>$data->pic4,
                        '6'=>$data->pic5,
                    ];
                    if (!empty($vposteris)) {
                        $rs = self::importVposteris($vposteris);
                        if($rs === false){
                            $flag = false;
                            throw exception("导入海报数据失败");
                        }
                        if (!empty($rs)) {
                            $vseriali->vposteris()->sync($rs);
                        }
                    }
                    //导入片源信息
                    if (!empty($data->file_url)) {
                        $rs = self::importVfiles($data);
                        if($rs === false){
                            $flag = false;
                            throw exception("导入媒资文件数据失败");
                        }else{
                            $vseriali->vifiles()->sync($rs);
                        }
                    }
                }else{
                    $flag = false;
                }

                if ($flag) {
                    DB::commit();
                } else {
                    DB::rollback();
                }
            }else{
                return '缺少主媒资数据,请先导入主媒资';
            }
        }catch (\Exception $e) {
            DB::rollback(); //事务回滚
            return $e->getMessage();
        }

        return $flag;
    }


    //导入SP数据
    public static function importSp($datas){
        $datas = explode(',',str_replace(array(',','/',' ','，'),',',$datas));
        //添加关联数据
        $ids = [];
        foreach ($datas as $filed_value){
            if(empty($filed_value)) continue;
            // 需要将SP编号转成id
            if ($sp1 = Sp::where('sp_no', $filed_value)->first()) {
                $ids[] = $sp1->id;
            } else {
                $sp             = new Sp;
                $sp->name       = $filed_value;
                $sp->short_desc = $filed_value;
                $sp->sp_no = $filed_value;
                $sp->save();
                $ids[] = $sp->id;
            }
        }
        if(empty($ids)) return false;
        return $ids;
    }

    //导入演员数据
    public static function importActors($datas){
        $datas = explode(',',str_replace(array(',','/',' ','，'),',',$datas));
        //添加关联数据
        $ids = [];
        foreach ($datas as $filed_value){
            if(empty($filed_value)) continue;
            // 需要将演员转为id
            if ($actor1 = Actor::where('name', $filed_value)->first()) {
                $ids[] = $actor1->id;
            } else {
                $actor             = new Actor;
                $actor->name       = $filed_value;
                $actor->short_desc = $filed_value;
                // 出生日期
                $actor->save();
                $ids[] = $actor->id;
            }
        }
        if(empty($ids)) return false;
        return $ids;
    }

    //导入Director数据
    public static function importDirector($datas){
        $datas = explode(',',str_replace(array(',','/',' ','，'),',',$datas));
        //添加关联数据
        $ids = [];
        foreach ($datas as $filed_value){
            if(empty($filed_value)) continue;
            // 需要将SP编号转成id
            if ($sp1 = Director::where('name', $filed_value)->first()) {
                $ids[] = $sp1->id;
            } else {
                $sp             = new Director;
                $sp->name       = $filed_value;
                $sp->short_desc = $filed_value;
                $sp->save();
                $ids[] = $sp->id;
            }
        }
        if(empty($ids)) return false;
        return $ids;
    }

    //导入地区数据
    public static function importVarea($datas){
        $datas = explode(',',str_replace(array(',','/',' ','，'),',',$datas));
        //添加关联数据
        $ids = [];
        foreach ($datas as $filed_value){
            if(empty($filed_value)) continue;
            // 需要将SP编号转成id
            if ($varea1 = Varea::where('name', $filed_value)->first()) {
                $ids[] = $varea1->id;
            } else {
                $varea             = new Varea;
                $varea->name       = $filed_value;
                $varea->short_desc = $filed_value;
                $varea->save();
                $ids[] = $varea->id;
            }
        }
        if(empty($ids)) return false;
        return $ids;
    }

    public static function importVlangs($datas){
        $datas = explode(',',str_replace(array(',','/',' ','，'),',',$datas));
        //添加关联数据
        $ids = [];
        foreach ($datas as $filed_value){
            if(empty($filed_value)) continue;
            // 需要将SP编号转成id
            if ($language1 = Vlang::where('name', $filed_value)->first()) {
                $ids[] = $language1->id;
            } else {
                $language             = new Vlang;
                $language->name       = $filed_value;
                $language->short_desc = $filed_value;
                $language->save();
                $ids[] = $language->id;
            }
        }
        if(empty($ids)) return false;
        return $ids;
    }

    public static function importVyears($datas){
        $datas = explode(',',str_replace(array(',','/',' ','，'),',',$datas));
        //添加关联数据
        $ids = [];
        foreach ($datas as $filed_value){
            if(empty($filed_value)) continue;
            // 需要将SP编号转成id
            if ($year1 = Vyear::where('name', $filed_value)->first()) {
                $ids[] = $year1->id;
            } else {
                $year             = new Vyear;
                $year->name       = $filed_value;
                $year->short_desc = $filed_value;
                $year->save();
                $ids[] = $year->id;
            }
        }
        if(empty($ids)) return false;
        return $ids;
    }


    public static function importVposteris($datas){
        //添加关联数据
        $ids = [];
        $http_server = config('custom.base.host.ftp');
        foreach ($datas as $imgtpl => $filed_value){
            if(empty($filed_value)) continue;
            // 新建图片
            $vposteri           = new Vposteri;
            $vposteri->name     = 'pic'.$imgtpl;
            $vposteri->title    = 'pic'.$imgtpl;
            $vposteri->subtitle = 'pic'.$imgtpl;
            $filePath             = $filed_value;
            $vposteri->href       = $http_server.$filed_value;
            $vposteri->vimgtag_id = 1;   //1海报  2剧照   3图集
            $vposteri->imgtpl_id  = $imgtpl;
            $vposteri->listorder  = 1;
            if ($vposteri->save()) {
                $ids[] = $vposteri->id;
            }
        }
        return $ids;
    }

    public static function importVfiles($data){

        $ids = [];
        // 存放视频的ftp
        // $ftp = FTP::connection();
        // var_dump($ftp);
        // return false;

        // 新建文件s
        $vifile                = new Vifile;
        $vifile->resolution_id = $data->resolutions;
        $vifile->vfileext_id   = $data->vformat;
        $vifile->title         = $data->title;
        $vifile->subtitle      = $data->subtitle;
        $vifile->name          = $data->title;
        $vifile->path   = $data->file_url;
        $vifile->size   = 0.00;
        $vifile->md5 = '';
        $vifile->duration   = $data->duration;
        $vifile->href       = $data->file_url;
        $vifile->short_desc = $data->short_desc;
        $vifile->long_desc  = $data->long_desc;
        $vifile->type       = 1;
        if ($vifile->save()) {
            $ids[] = $vifile->id;
        }
        return $ids;
    }


}
